from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django import forms
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import authenticate, login
from django.utils import simplejson
from django.forms import ModelForm

from django.core.paginator import Paginator, InvalidPage, EmptyPage


from tagging.fields import TagField
from tagging.models import Tag

from ceemtu.cetphoto.models import *

class PhotoForm(ModelForm):
    tags = TagField()
    class Meta:
        model = Photo

def index(request):
    return render_to_response(
        "photo/index.html",
        {'photos' : Photo.objects.all()},
        RequestContext(request, {}),
    )
    return render_to_response("photo/index.html", RequestContext(request, {}))

def clear_selected_photos(request):
    request.session['selected_photos'] = []
    return HttpResponse('<xml><result>selection cleared</result></xml>', mimetype="text/xml")

def selected_photos_json(request):
    print request.POST
    selected_photos = request.session.get('selected_photos', [])
    photos = Photo.objects.filter(pk__in = selected_photos)
    _d = []
    for photo in photos:
        _d.append({'photo_id': photo.id, 'image_url': photo.thumbnail_url()})
    data = {'items': tuple(_d)}
    import json
    return HttpResponse(json.dumps(data), mimetype="text/json")

def ajax_test(request):
    #import pdb
    #pdb.set_trace()
    print request.POST
    _photo_id = request.POST.get('photo_id', None)
    _action = request.POST.get('action', None)
    selected_photos = request.session.get('selected_photos', [])
    if _photo_id:# and _action == 'add_photo':
        try:
            result = 'hmmmm'
            if not selected_photos:
                selected_photos = [_photo_id]
            else:
                result = 'selected'
                if not _photo_id in selected_photos:
                    selected_photos.append(_photo_id)
                else:
                    result = 'not selected'
                    selected_photos.remove(_photo_id)
            request.session['selected_photos'] = selected_photos
            xml_response = """
            <xml_response>
                <selected_count>%s</selected_count>
                <current_status>%s</current_status>
            </xml_response>""" % (len(selected_photos), result)
            print xml_response
            return HttpResponse(xml_response, mimetype="text/xml")
        except Exception, e:
            print "Exception", e
    #rating = request.POST.get('rating', -1)
    #xml = "<ratings><average>%s</average><count>%s</count></ratings>" % (1, rating)
    #return HttpResponse(xml, mimetype="text/xml")

def view_photos(request, _year, _month = None, _day = None):
    """
    
    """
    if _year and _month and _day:
        photos = Photo.objects.filter(year = _year, month = _month, day = _day)
    elif _year and _month:
        photos = Photo.objects.filter(year = _year, month = _month)
    elif _year:
        photos = Photo.objects.filter(year = _year)

    paginator = Paginator(photos, 10) # Show 25 contacts per page

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        _photos = paginator.page(page)
    except (EmptyPage, InvalidPage):
        _photos = paginator.page(paginator.num_pages)
    selected_photos = request.session.get('selected_photos', [])

    return render_to_response('photo/list.html', {"photos": _photos, 'selected_photos': selected_photos})
view_photos = staff_member_required(view_photos)

def image_details(request, photo_id):
    photo = get_object_or_404(Photo, pk=photo_id)
    form = PhotoForm(instance=photo)

    return render_to_response(
        "photo/details.html",
        {
            'photo' : photo,
            'form': form
            },
        RequestContext(request, {}),
    )

image_details = staff_member_required(image_details)

def get_image(request, size, photo_id):
    photo = get_object_or_404(Photo, pk=photo_id)
    return HttpResponseRedirect('/static/generated/%s' % photo.get_image(size))
get_image = staff_member_required(get_image)